<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Canvas</title>
    <style type="text/css">
        body {
            text-align: center;
            padding-top: 20px;
        }
        canvas {
            box-shadow: 0 0 10px #333;
            margin: 0 auto;
        }
    </style>
</head>
<body onload="draw()">
<canvas id="canvas" width="800" height="600">
    你的浏览器太 low 了，请更新~!
</canvas>

<script>
    function draw() {
        var canvas = document.getElementById("canvas");
        if (canvas.getContext) {
            var ctx = canvas.getContext('2d');

            function Rect(x, y, width, height, color, speed) {
                this.x = x;
                this.y = y;
                this.width = width;
                this.height = height;
                this.color = color;
                this.speed = speed;
            }

            Rect.prototype.draw = function () {
                ctx.beginPath();
                ctx.fillStyle = this.color;
                ctx.fillRect(this.x, this.y, this.width, this.height);
                ctx.closePath();
            };

            Rect.prototype.move = function () {
                this.x += this.speed;

                if (this.x >= canvas.width - this.width || this.x < 0) {
                    this.speed *= -1;
                }
            };

            // 常见两个矩形
            var rect1 = new Rect(0, 100, 100, 100, 'red', 2);
            var rect2 = new Rect(700, 100, 100, 100, 'blue', -2);
            rect1.draw();
            rect2.draw();

            function animate() {
                ctx.clearRect(0, 0, canvas.width, canvas.height);

                rect1.draw();
                rect2.draw();
                rect1.move();
                rect2.move();

                if (isRectHit(rect1, rect2)) {
                    rect1.speed *= -1;
                    rect2.speed *= -1;
                }
                window.requestAnimationFrame(animate);
            }

            animate();

            function isRectHit(rect1, rect2) {
                // 获取矩形的最小x和最大x
                var min1 = rect1.x;
                var min2 = rect2.x;

                var max1 = rect1.x + rect1.width;
                var max2 = rect2.x + rect2.width;

                var min3 = Math.max(min1, min2);
                var max3 = Math.min(max1, max2);

                return min3 < max3;
            }
        }
    }
</script>
</body>
</html>
